package cr.co.tse.padronelectoral.csv;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

/**
 * This dao was useful to parser the fix field file.
 * @author jsanca
 *
 */
public class JuntaRowReaderDAOImpl implements RowReaderGenericDAO {

	private LineNumberReader reader = null;

	public JuntaRowReaderDAOImpl(File file) throws FileNotFoundException {

		this.reader = new LineNumberReader(new FileReader(file));
	}

	@Override
	public String[] next() throws IOException {
		
		String line = this.reader.readLine();
		List<String> columns = null;
		int beginIndex = 0;
		
		if (null != line) {
			
			columns = new ArrayList<String> ();
			beginIndex = this.getBeginIndex(line);
			beginIndex = this.nextDireccion (line, beginIndex, columns);
			beginIndex = this.nextJuntaNumero (line, beginIndex, columns);
			beginIndex = this.nextJuntaNumero (line, beginIndex, columns);
			this.nextNombreJunta (line, beginIndex, columns);
			
		}
		
		return (null != columns)?
				(String[]) columns.toArray(new String[]{}):null;
	}

	private int nextJuntaNumero(String line, int beginIndex,
			List<String> columns) {
		
		char c = '\0';
		StringBuilder builder = new StringBuilder ();
		int i = beginIndex;
		c = line.charAt(i++);
		while (!Character.isDigit(c)) {
			
			c = line.charAt(i++);
		}

		builder.append(c);
		c = line.charAt(i++);
		
		while (' ' != c) {
			
			builder.append(c);
			c = line.charAt(i++);
		}
		
		columns.add(builder.toString());
		
		return i;
	}

	private void nextNombreJunta(String line, int beginIndex,
			List<String> columns) {
		
		columns.add(line.substring(beginIndex));
	}

	private int nextDireccion(String line, int beginIndex, List<String> columns) {

		char c = '\0';
		StringBuilder builder = new StringBuilder ();
		int i = beginIndex;
		c = line.charAt(i++);
		while (!Character.isDigit(c)) {
			
			builder.append(c);
			c = line.charAt(i++);
		}
		
		columns.add(builder.toString());
		
		return i-1;
	}

	public int getBeginIndex (String line) {
		
		int i = 1;
		while (' ' != line.charAt(i++));
		
		return i;
	}
	
	@Override
	public void close() throws IOException {

		if (null != reader) {

			reader.close();
		}
	}

}
